<?php

namespace common\Amqp;

use common\Factory\Factory;

class WriteLog {
    
    private $_isConnect = false;
    private $_rabbitMq;
    private $_exchangeName;
    
    function __construct() {
        $this->_rabbitMq = Factory::getServer('Rabbitmq');
        $config = \core\init\init::getConfig();
        if(isset($config['rabbitmq'])) {
            $this->_exchangeName = $config['rabbitmq']['exchangeName'];
        }
    }
    
    public function connect() {
        if(!$this->_rabbitMq->isConnected()) {
            $this->_rabbitMq->connect();
            $this->_isConnect = true;
        }
    }
    
    public function disConnect() {
        $this->_rabbitMq->disconnect();
    }
    
    public function send($massage, $isDisConnect = false) {
        $this->_isConnect === false && $this->_isConnect = $this->_rabbitMq->connect();
        if($this->_isConnect !== false) {
            if((string)trim($massage) != '') {
                $channel = new \AMQPChannel($this->_rabbitMq);
                //创建交换机对象
                $ex = new \AMQPExchange($channel);
                $ex->setName($this->_exchangeName);
                $return = $ex->publish($massage, 'writeLogKey');
                $isDisConnect === true && $this->_rabbitMq->disconnect();

                return $return;
            }
        }
        
        return false;
    }
    
    public function receive() {
        $this->_isConnect === false && $this->_isConnect = $this->_rabbitMq->connect();
        if($this->_isConnect !== false) {
            $channel = new \AMQPChannel($this->_rabbitMq);
            //创建交换机对象
            $ex = new \AMQPExchange($channel);
            $ex->setName($this->_exchangeName);
            //direct类型
            $ex->setType(AMQP_EX_TYPE_DIRECT); 
            //持久化
            $ex->setFlags(AMQP_DURABLE);
            $ex->declareExchange();
            
            //创建队列
            $q = new \AMQPQueue($channel);
            $q->setName('writeLog');
            //持久化
            $q->setFlags(AMQP_DURABLE);
            $q->declareQueue();
            $q->bind($this->_exchangeName, 'writeLogKey');
            
            //阻塞模式接收消息
            //自动ACK应答
            $q->consume(array($this, 'write'), AMQP_AUTOACK); 
            $this->_rabbitMq->disconnect();
        }

        return false;
    }
    
    public function write($envelope, $queue) {
        $massage = $envelope->getBody();
        Factory::getServer('Logger')->debug($massage);
    }
}